﻿using System;
using System.IO;
using System.Windows.Forms;
using Moonlite.ExtensionApi.GlobalInterfaces;

namespace Moonlite.Platform.Text.File
{
    public static class SnippetParser
    {
        private static SnippetCollection snippets;
        public static SnippetCollection Snippets
        {
            get
            {
                if (snippets == null)
                {
                    snippets = GetAllSnippets();
                }

                return snippets;
            }
        }

        public static ISnippet ParseSnippet(string filename)
        {
            if (!System.IO.File.Exists(filename))
            {
                throw new IOException("File does not exist.");
            }

            Snippet snippet = new Snippet();
            snippet.File = filename;
            using (StreamReader reader = new StreamReader(filename))
            {
                snippet.Content = reader.ReadToEnd();
            }

            return snippet;
        }

        public static SnippetCollection GetAllSnippets()
        {
            string directoryPath = Application.StartupPath + "\\Snippets";
            SnippetCollection snippets = new SnippetCollection();
            DirectoryInfo info = new DirectoryInfo(directoryPath);
            Array.ForEach(info.GetFiles("*.csn"), fileInfo =>
            {
                ISnippet snippet = ParseSnippet(fileInfo.FullName);
                if (snippet != null)
                {
                    snippets.Add(snippet);
                }
            });

            return snippets;
        }
    }
}
